<?php
/**
 * beimuaihui System
 * Copyright(c) 2011-2020 beimuaihui.
 * @license    http://www.gnu.org/licenses/gpl.html     This software Under GPL V3 License 
 * beimuaihui@gmail.com
 * http://code.google.com/p/beimuaihui/
 * $Id: ContentinfoController.php 465 2012-02-12 05:33:23Z beimuaihui $
 */



class Mall_ContentinfoController extends Baogg_Controller_Action {

	function init() 
	{
		Zend_Loader::loadClass ( 'Content' );
		
		$model_id=$this->getRequest()->getParam('model_id',0);
		$this->content = new Content ( );
		
		$this->model=new ModelTable($model_id);
	}

	/**
	 * The default action
	 */
	public function listAction() {
		global $LANG;
		
		$model_id=$this->getRequest()->getParam('model_id');
		
		Zend_Loader::loadClass('ModelField');
		$modelField=new ModelField();
		$rs=$modelField->getList(array("model_id"=>$model_id,"state"=>1),array("sort"=>"ordering","dir"=>"asc"));
		
		Zend_Loader::loadClass("Baogg_View_Extgrid");
		
		$cm=array();
		foreach((array)$rs as $v){
			$cm[$v['field_name']]=array("header"=>$v['show_name']);
			if($v['field_key']=='PRI' ){
				$cm[$v['field_name']]['cmType']=Baogg_View_Extgrid::CMTYPE_PK;
			}
			if(!$v['is_basic']){
				$cm[$v['field_name']]['hidden']=true;
			}
		}
		
		$count=count((array)$rs);
		$column_count=floor($count / 3);
		$column_count_extra= $count % 3;
		$column_pos=array(0,0,0);
		$field_items=array();
		for($i=0;$i<3;$i++){			
			$column_pos[$i]+=($i>0?$column_pos[$i-1]:0)+$column_count + ($column_count_extra>$i?1:0);
			$field_items[$i]=array("columnWidth"=>"0.3","layout"=>"form");
		}
		//echo '<pre>';print_r($column_pos);var_dump($count);exit;
		$pos=0;
		foreach((array)$rs as $k=>$v){
			if($k>=$column_pos[$pos]){
				$pos++;
			}			
			$item=array("xtype"=>$v['field_view'],
				"fieldLabel"=>$v['show_name'],
				"name"=> $v['field_name'],
				"anchor"=> '95%'
			);
			
			$source=ModelTable::handleFieldOptions($v['field_options']);
			if($v['field_view']=='combo'){				
				$item=array_merge($item,array(
					 "fields"=>array('id','text'),
                         "store"=>$source,
                         "name"=>$v['field_name'].'2',
                         "submitValue"=>"false",
                         "hiddenName"=>$v['field_name'],
                         "displayField"=>'text',
                         "valueField"=>'id'
				));
			}else if($v['field_view']=='radiogroup'){
				foreach((array)$source as $opt){
					$item['items'][]=array(
						 'xtype'=> 'radio',
                         "inputValue"=> $opt[0],
                         "name"=> $v['field_name'],
                         "boxLabel"=> $opt[1],
					);
				}
			}else if($v['field_view']=='checkboxgroup'){
				foreach((array)$source as $opt){
					$item['items'][]=array(
						 'xtype'=> 'checkbox',
                         "inputValue"=> $opt[0],
                         "name"=> $v['field_name'],
                         "boxLabel"=> $opt[1],
					);
				}
			}else if($v['field_view']=='htmleditor'){
				$item['height']='300';
				$item['width']='600';
				unset($item['anchor']);
			}
			
			$field_items[$pos]['items'][]=$item;
			
		}
		$json_field_items=Zend_Json::encode($field_items);
		
		
		//$cm['sub_table']=array("hidden"=>true,"cmType"=>Baogg_View_Extgrid::CMTYPE_SUBTABLE) ; //Baogg_View_Extgrid::;
		
		
		$grid=new Baogg_View_Extgrid(BAOGG_BASE_URL."mall/content/data/model_id/{$model_id}", $cm);
		$grid->setSelectionModel(true);
		$grid->setRowNumberer(true);
	//$grid->registerButton("delete","grid.deleteSelected('".BAOGG_BASE_URL."mall/content/delete/model_id/{$model_id}')");
		
		$this->view->form_url=BAOGG_BASE_URL."mall/content/save/model_id/{$model_id}";
		$this->view->LANG=Zend_Json::encode($LANG);
		$this->view->json_field_items=$json_field_items;
		$this->view->grid = $grid->render();
		
		//echo '<pre>';var_dump($LANG);exit;


	}

	/**
	 * The data action
	 */
	function dataAction() {
	    $post=$this->_request->getPost ();
	    $where=array();$order=array();$limit=array();
	   foreach((array)$post as $k=>$v){
	       if($k=="start" || $k=="limit"){
	           $limit[$k]=$v;
	       }else if($k=="sort" || $k=="dir"){
	           $order[$k]=$v;
	       }else{
	           if($k=="content_id"  ){
	               if($v && is_numeric($v)){
	                   $v=(int)$v;
	                   $where[$k]=$v;
	               }
	           }else{
	               $v='%'.$v.'%';
	               $where[$k]=$v;
	           }
	           
	       }
	   }
	   $data=$this->content->getModelList($where,$order,$limit,$this->model->getName());
	   // echo Baogg_Db::debugDb(Zend_Registry::get("db"));exit;
	   $this->view->grid = Zend_Json::encode(array("count"=>"1","data"=>$data));
	}

	
	/**
	 * The add action
	 */
	function addAction(){
		if ($this->_request->isPost ()) {
			$this->saveAction();
		}else{
			$this->editAction();
			$this->_helper->viewRenderer->render ( 'edit' );
		}
	}
	
	/**
	 * The edit action
	 */
	function editAction() {
		

	/*	$id = (int)Baogg_Controller_Action::_getParam ( 'id' );
		if ($id>0) {
			$rows = $this->content->getOne ( $id );
			$list=$rows[0];
			$action="edit";
			$urlParam="/id/".$id;
		} else {
			$action="add";
			$urlParam="";
			$list["state"]=1;
		}

		//toolbar
		Loader::loadClass('ext::toolbar');
		$this->view->toolbarButton = new extToolBar();
		$this->view->toolbarButton->registerButton ($multiLang->g_save, "handleForm('adminForm',\"{$config['web']['baseurl']}multilang/content/save{$urlParam}\")", 'save-icon' );
		$this->view->toolbarButton->registerButton ( $multiLang->g_cancel, 'parent.dialog.hide()', 'cancel-icon' );
		//form
		Loader::loadClass('form');
		$handleform = new form_element();
		$form = $this->content->getForm ();
		if(!$list){
			//$_list=array_fill_keys(array_keys($form['elements']),"");
			//$list[0]=$_list;
		}
		//$list[0]['action']
		$form = $handleform->handleArray($form['options'],$form['elements'], $list,$action);
		$this->view->form = $form;*/
	}

	/**
	 * The delete action
	 */
	function deleteAction() {
        
	    $ret=array("success"=>false,"msg"=>"delete_fail");
	    $id = Baogg_Controller_Action::_getParam ( 'ids' );
		$flag=$this->content->_delete ( $id );
		
		$flag=$flag && $this->model->_delete($id);

		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));
		
		if ($flag){
			$ret['success'] = true;
			$ret["msg"]="delete_ok";
		}
		
		echo Baogg_Language::outputResult($ret);
		   exit;
		/*$this->_helper->viewRenderer->setNoRender ();
		$log=array();
		$log['module_permission_id'] 	= getPermissionId();
		$log['contents_id']				= $_SESSION['s_admin_content_id'];
		$log['message']					= $message;
		$log['log_sql']					= debugDb();
		$log['result']					= $flag;
		$log['log_contents_id']			= $_SESSION['s_admin_content_id'];
		//print_r($log);
		insertLog($log);*/
		
		
	}

	/**
	 * The save action
	 */
	function saveAction() {
		//global $LANG;
		
	    $ret=array("success"=>false,"msg"=>"save_fail");
	    
	    //check form
		if (!$this->_request->isPost ())
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;
		}
		
		$formData = $this->_request->getPost ();

		if(!$formData)
		{
		   echo Baogg_Language::outputResult($ret);
		   exit;     
		}
			
		$arr=$this->content->filterForm($formData);
		$arr_model=$this->model->filterForm($formData);
		
       // echo '<pre>';print_r($arr);exit;
		$rs = $this->content->getSame($arr);
		if(($arr["content_id"])>0){
			//update record
			//$permission_type = 2;
			//echo '<pre>';print_r($rs);var_dump(count($rs));exit;
			if( count($rs)==1 &&  $rs[0] == $arr["content_id"] ){
			    $this->content->_update($arr,$arr["content_id"]);
			    $this->model->update($arr_model, "content_id={$arr_model['content_id']}");
			    $ret['success'] = true;				
				$ret['msg'] = "save_ok";			
			}else{
				$ret['msg'] = "exist_same_record";
			}
			
		}else{
			//insert record
			//$permission_type = 1;			
			if($rs){				
				$ret['msg'] = "exist_same_record";
			}else{
			    unset($arr["content_id"]);
			    $content_id= $this->content->_insert($arr);
			    $arr_model['content_id']=$content_id;
				$ret['success'] =$this->model->insert($arr_model)?true:false;
				
				$ret['msg'] = "add_ok";
			}
		}
				
		echo Baogg_Language::outputResult($ret);
		//echo Baogg_Db::debugDb(Zend_Registry::get('db'));
		$this->_helper->viewRenderer->setNoRender ();
		
		
	}

}
